<?php
if( !defined('IN_INDEX') )
{
	die('This page is hidden.');
}

if(!checkSession())
{
			function redirect($url)
			{
			?>
				<script type="text/javascript">
					{
					window.location = "<?=$url?>";
					}
				</script>
			<?php 
			}
			redirect("index.php?action=login");
	exit;
}
include('inc/functions_blog.php');



$dateformat_long = $CONFIG['date_format_long'];

?>


<link rel="stylesheet" href="./jscript/prettyphoto/css/prettyPhoto.css" type="text/css" media="screen" charset="utf-8" />
<link rel="stylesheet" href="./jscript/video.css" type="text/css" media="screen" charset="utf-8" />
<script src="./jscript/prettyphoto/js/jquery.prettyPhoto.js" type="text/javascript" charset="utf-8"></script>
<script src="./jscript/video.js" type="text/javascript" charset="utf-8"></script>


<div id='postpath'>
		<a title="<?php echo translate('gotofrontpage'); ?>" href="index.php"><?php echo translate('home'); ?></a>
		 &gt; <a href="index.php?action=home&sub=videos" title='<?php echo translate('videos'); ?>'><?php echo translate('videos'); ?></a> 
</div>
<br />
<?php
if(isset($_POST) && count($_POST) >0){
	$userSelectedType = $_POST['user-selected-type'];
	
	if(isset($_POST['selectedUser'])){
		//print_r($_POST['selectedUser']);
		$selectedUserList = $_POST['selectedUser'];
		if(count($selectedUserList) >0){
			$selectedUserString = "";
			foreach ($selectedUserList as $userId){
				$selectedUserString .= $userId.",";
			}
			$selectedUserString =  substr($selectedUserString, 0, strlen($selectedUserString)-1);
		}
	}
	$selectcategory = $_POST['select_category'];
	$selectexercise = $_POST['select_exercise'];
	if(is_numeric($_POST['weight-from'])){
		$weightFrom = $_POST['weight-from'];
	}else{
		$weightFrom = 0;
	}
		
	if(is_numeric($_POST['weight-to'])){
		$weightTo = $_POST['weight-to'];
	}else{
		$weightTo = 1000000;
	}
	$sql = "SELECT
	DISTINCT lifts.training_id,
	lifts.kg,
	lifts.rep,
	lifts.url,
	lifts.exercise_id,
	training.date, 
	training.place,
	training.user_id,
	users.user_country,
	training.bodyweight
	FROM lifts, training, users
	WHERE training.training_id=lifts.training_id AND lifts.url != '' AND training.user_id=users.user_id AND (lifts.kg > ".$weightFrom." AND lifts.kg < ".$weightTo.")";
		
	if(trim($selectexercise) != ""){
		$sql .= " AND lifts.exercise_id = ".$selectexercise;
	}else{
		if($selectcategory != ""){
			$selectExerciseStr = "";
			$exList = $EXERCISE_LIST[$selectcategory]['list'];
			if(count($exList) > 0){
				foreach($exList as $k => $v)
				{
					$selectExerciseStr .=  $v['id'].",";
				}
			}
			if(strlen($selectExerciseStr) > 0){
				$selectExerciseStr = substr($selectExerciseStr, 0, strlen($selectExerciseStr)-1);
				$sql .= " AND lifts.exercise_id IN (".$selectExerciseStr.")";
			}
		}
	}
	
	if(($userSelectedType != "all-user") && isset($selectedUserList)){
		$sql .= " AND training.user_id IN ('".$selectedUserString."') ";
	}
	
	$sql .= " ORDER BY -training.date LIMIT 100";
	//echo $sql;
	$result = mysql_query($sql) or die (mysql_error());
}else{
	$result = mysql_query("SELECT
	lifts.kg,
	lifts.rep,
	lifts.url,
	lifts.exercise_id,
	training.training_id,
	training.date, 
	training.place,
	training.user_id,
	users.user_country,
	training.bodyweight
	FROM lifts, training, users
	WHERE training.training_id=lifts.training_id AND lifts.url != '' AND training.user_id=users.user_id
	ORDER BY -training.date LIMIT 100") or die(mysql_error());

}
?>

<form action="" method="POST" name="search_video">
	<div class="select-user-wrapper">
		<div class="select-user">
			<a id="pick-user" href="#">Pick user /</a> <a id="all-user" href="#"><?php echo translate('all') ?> /</a> <a id= "group-user" href="#"><?php echo translate('groups'); ?> /</a> <a id="my-following" href="#"><?php echo translate('myfollowing_show') ?></a>
			<div id="user-box" style="display: none;">
				<input id="select-all-user" onchange="selectAlluser();" type="checkbox" value="" /><span><?php echo translate('select')." ".translate('all'); ?></span>
				<div id="user-list">
				</div>
			</div>
			<div id="selected-user-list">
			</div>
		</div>
		<div class="select-exercise-wrapper">
			<select class="selectbox"  id="select_category" name="select_category" onchange="updateOptions(document.search_video.select_category.options[document.search_video.select_category.selectedIndex].value, 'select_exercise');">
				<option value="" selected="selected">
				<?php echo translate('select_category'); ?>
				</option>
				<?php
			 
				foreach($EXERCISE_LIST as $key => $value)
				{
					$ex_id = $value['id'];
					
					$ex_list = $value['list'];
					$output = translate($value['name']);
					if(isset($selectcategory) && ($selectcategory != "") && ($selectcategory == $key)){
				?>
					<option value="<?php echo $key ?>" selected="selected"><?php echo  translate($output) ?></option>
				<?php
					}else{
				?>
					<option value="<?php echo $key ?>"><?php echo  translate($output) ?></option>
				<?php
					}
				}
				?>
			</select> 
			<select id="select_exercise" name="select_exercise" class="selectbox"  onchange="javascript:selected_exercise(this.value);" >
			<?php
				if(!isset($selectcategory) || ($selectcategory =="")){
			?>
				<option value="" selected="selected">
				<?php echo translate('selectcategoryfirst'); ?>
				</option>
			<?php
				}else{
			?>
				<option value="" selected="selected">
				<?php echo translate('selectexercise'); ?>
				</option>
			<?php
					$exTempList = $EXERCISE_LIST[$selectcategory]['list'];
					if(count($exTempList) > 0){
						foreach($exTempList as $k => $v)
						{
							if(isset($selectexercise) && ($selectexercise == $v['id'])){
			?>
				<option value="<?php echo $v['id']?>" selected="selected">
				<?php echo translate($v['name']); ?>
				</option>			
			<?php
						
							}else{
			?>
				<option value="<?php echo $v['id']?>">
				<?php echo translate($v['name']); ?>
				</option>
			<?php
							}
						}
					}
			?>
			<?php
				}
			?>
			</select>
		</div>
		<div style="clear:both;"></div>
		<div class="select-weight">
			<input id="weight-from" type="text" onclick="EmptyOnClick('weight-from')" value ="<?php if(!isset($weightFrom) || $weightFrom == 0){echo "Weight from"; }else{ echo $weightFrom;}?>" name="weight-from" />
			<input id="weight-to" type="text" onclick="EmptyOnClick('weight-to')" value ="<?php if(!isset($weightTo) ||$weightTo == 1000000){echo "Weight to"; }else{ echo $weightTo;}?>" name="weight-to" /> <span><?php echo translate('kg'); ?></span>
			<input name="submit" type="submit" value="<?php echo translate('show_video'); ?>" />
		</div>
		<input name="user-selected-type" id="user-selected-type" type="hidden" value="<?php echo isset($userSelectedType)? $userSelectedType: "";?>" />
		<div style="clear:both;"></div>
	</div>
</form>
<?php
	if(isset($_POST) && count($_POST) >0){
?>
	<h1> <img src='img/videos.png' /> <?php echo ucf(translate('videos')); ?></h1>
	<br />
<?php
	}else{
?>
	<h1> <img src='img/videos.png' /> <?php echo ucf(translate('latestvideos')); ?></h1>
	<br />
<?php
	}
?>

<?php 
		// keeps getting the next row until there are no more to get
		if(count($result) > 0){
			$i = 0;
			
			$tempVideoList = array();
			while($row = mysql_fetch_array($result)) 
			{
				$isExisted = false;
				if(count($tempVideoList) >0){
					foreach($tempVideoList as $tempRow){
						if($tempRow['url'] == $row['url'] ){
							$isExisted = true;
							break;
						}
					}
				}
				if($isExisted){
					continue;
				}else{
					$tempVideoList [] = $row;
				}
				$i++;
				$videoInfor = getVideoInfor($row['url']);
				if(!$videoInfor){
					// Print out the contents of each row into a table
					echo "<div style='float: left; clear: right; padding-right: 2px;'><a style='color:#555555;' href='" . $row['url'] . "' rel='prettyPhoto' title='". translate('show_video') ."'><img src='img/flags/16/" . strtolower($row['user_country']) . ".png' /></div> <b>";
					echo getNameFromId($row['user_id']) . "</b> " . strtolower(translate('lifted')) . " <b>";
					
					if($w_metric == "kg")
					{
					echo r_nr2(calcFromKg($row['kg'])). $w_metric . " x " . $row['rep'];
					}
					else
					{
					echo r_nr(calcFromKg($row['kg'])). $w_metric . " x " . $row['rep'];
					}
					
					echo " " . translate('i') . " " . strtolower(translate(getExercisename($row['exercise_id']))) . " " . strtolower(translate('on')) . " " . r_nr2(calcFromKg($row['bodyweight'])). $w_metric . " " . strtolower(translate('bodyweight'));
					echo "</b> @ " . $row['place'] . " " . translate('for'). " ";
					echo getHowLongAgo($row['date']) . ".</a>";
					echo "<br /><br />";
				}else{
					echo "<div style='width: 800px;'>";
					echo 	"<div style='float: left; width: 120px; position: relative; margin: 0 15px 20px 0;'>";
					echo 		"<a style='color:#555555;' href='" . $row['url'] . "' rel='prettyPhoto' title='". translate('show_video') ."'><img src='".$videoInfor['thumbnail']."' /><span style=' position: absolute; bottom: 0; right: 0; background-color: #000000; color: #FFFFFF; font-size: 11px;'>".secondsToTime($videoInfor["seconds"])."</a>";
					echo 	"</div>";
					echo 	"<div style='float: left; width: 600px;'>";
					echo 		"<p><b><a style='color:#0033CC;' href='" . $row['url'] . "' rel='prettyPhoto' title='". translate('show_video') ."'>".$videoInfor['title']."</a></b></p>";
					echo 		"<span>".$videoInfor["content"]."</span><br/>";
					echo 		"<span>by</span> <span><a href='http://www.youtube.com/".$videoInfor["author"]."' style='color:#0033CC;'>".$videoInfor["author"]."</a></span> <span>".dayToDateString(substr($videoInfor["published"], 0, 9))."</span><br/><span><b>".$videoInfor['viewCount'] ." ".translate('views')."</b></span><br/>";
					echo		"<a class='goto-workout-link' href='index.php?action=profile&sub=show&tid=".$row['training_id']."'>".translate('gotoworkout')."</a>";
					echo 	"</div>";
					echo	"<div style='clear: both;'></div>";
					echo "</div>";
				}
				/*
				// Print out the contents of each row into a table
				echo "<div style='float: left; clear: right; padding-right: 2px;'><a style='color:#555555;' href='" . $row['url'] . "' rel='prettyPhoto' title='". translate('show_video') ."'><img src='img/flags/16/" . strtolower($row['user_country']) . ".png' /></div> <b>";
				echo getNameFromId($row['user_id']) . "</b> " . strtolower(translate('lifted')) . " <b>";
				
				if($w_metric == "kg")
				{
				echo r_nr2(calcFromKg($row['kg'])). $w_metric . " x " . $row['rep'];
				}
				else
				{
				echo r_nr(calcFromKg($row['kg'])). $w_metric . " x " . $row['rep'];
				}
				
				echo " " . translate('i') . " " . strtolower(translate(getExercisename($row['exercise_id']))) . " " . strtolower(translate('on')) . " " . r_nr2(calcFromKg($row['bodyweight'])). $w_metric . " " . strtolower(translate('bodyweight'));
				echo "</b> @ " . $row['place'] . " " . translate('for'). " ";
				echo getHowLongAgo($row['date']) . ".</a>";
				echo "<br /><br />";
				*/
			}
			//echo $i." videos";
		}
?>

<script type="text/javascript" charset="utf-8">
  $(document).ready(function(){
    $("a[rel^='prettyPhoto']").prettyPhoto();
	
	$("#pick-user").click( function (){
		$("#all-user").removeClass("selected-user-link");
		$("#group-user").removeClass("selected-user-link");
		$("#my-following").removeClass("selected-user-link");
		
		$("#pick-user").addClass("selected-user-link");
		
		if($('#user-box').is(':data(dialog)') && ($("#user-selected-type").val() == "pick-user") ){
			$('#user-box').dialog('open');
		}else{
			$("#user-selected-type").val("pick-user");
			$("#selected-user-list").html('');
			$.post("index2.php",{action:'user', sub: 'video',task:'get_all_user'}, function(res){
       			$('#user-list').html(res);
       		 });
		
			
			$("#user-box").dialog(
				{ 
					title: "<?php echo translate('select')." ".translate('user')?>",
					dialogClass: 'dialog',
					width:550,
					height:500,
					buttons: [
							    {
								   text: "OK",
								   click: function(){ 
										$(this).dialog("close"); 
									}
							    }
						    ] 
				}
			);
		}
		return false;
	});
	
	$("#all-user").click (function (){
		$("#user-selected-type").val("all-user");
		$("#all-user").addClass("selected-user-link");
		$("#pick-user").removeClass("selected-user-link");
		$("#group-user").removeClass("selected-user-link");
		$("#my-following").removeClass("selected-user-link");
		if($('#user-box').is(':data(dialog)')){
			$('#user-box').dialog('close');
		}
		
	});
	$("#group-user").click (function (){
		$("#user-selected-type").val("all-user");
		$("#group-user").addClass("selected-user-link");
		$("#pick-user").removeClass("selected-user-link");
		$("#all-user").removeClass("selected-user-link");
		$("#my-following").removeClass("selected-user-link");
		if($('#user-box').is(':data(dialog)')){
			$('#user-box').dialog('close');
		}
		
	});
	$("#my-following").click (function (){
		$("#my-following").addClass("selected-user-link");
		$("#pick-user").removeClass("selected-user-link");
		$("#group-user").removeClass("selected-user-link");
		$("#all-user").removeClass("selected-user-link");
		
		if($('#user-box').is(':data(dialog)') && ($("#user-selected-type").val() == "my-following") ){
			$('#user-box').dialog('open');
		}else{
			$("#user-selected-type").val("my-following");
			$("#selected-user-list").html('');
			$.post("index2.php",{action:'user', sub: 'video',task:'get_following_user'}, function(res){
       			$('#user-list').html(res);
       		 });
		
			
			$("#user-box").dialog(
				{ 
					title: "<?php echo translate('select')." ".translate('user')?>",
					dialogClass: 'dialog',
					width:550,
					height:500,
					buttons: [
							    {
								   text: "OK",
								   click: function(){ 
										$(this).dialog("close"); 
									}
							    }
						    ] 
				}
			);
		}
		return false;
	});
  });
	function selectedUser($id, $userId){
		if($("#"+$id).is(':checked')){
			$("#selected-user-list").append('<input id="selectedUser'+$userId+'" type="hidden" name="selectedUser[]" value="'+$userId+'" />');
		}else{
			//$("#selected-user-list").remove('#selectedUser'+$userId);
			$('#selectedUser'+$userId).remove();
		}
	}
	
	function selectAlluser(){
		if($("#select-all-user").is(':checked')){
			//$("#user-list > div > input").attr('checked','checked');
			$("#user-list > div > input").each(function(){
				$(this).attr('checked','checked');
				$("#selected-user-list").append('<input id="selectedUser'+$(this).attr('value')+'" type="hidden" name="selectedUser[]" value="'+$(this).attr('value')+'" />');
			});
		}else{
			//$("#user-list > div > input").attr('checked',false);
			$("#user-list > div > input").each(function(){
				$(this).attr('checked',false);
				$('#selectedUser'+$(this).attr('value')).remove();
			});
		}
		
	}
	
	// Dropdown boxes
	function updateOptions(chosen, nameofbox)
	{
		var selbox = document.getElementById(nameofbox);
		selbox.options.length = 0;
		 
		if (chosen == "") 
		{
			selbox.options[selbox.options.length] = new Option('<?php echo translate("selectcategoryfirst"); ?>','');
		}else{
			selbox.options[selbox.options.length] = new Option('<?php echo translate('selectexercise'); ?>','');
			<?php
			foreach($EXERCISE_LIST as $key => $value)
			{
				$ex_id = $value['id'];
				$ex_list = $value['list'];
				$output = translate($value['name']);
				echo "if(chosen == \"" . $key . "\") {\n";
				foreach($ex_list as $k => $v)
				{
					$output = translate($v['name']);
					echo "	selbox.options[selbox.options.length] = new Option('" . $output . "', '" . $v['id'] . "');\n";
				}
				echo "}\n";
			}
			?>
		}
	}
</script>